import { useEffect, useState } from "react";
import { TableContainer, TableHeader } from "../../../csscomponents/base";
import { Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import {
  PlusOutlined,
  SearchOutlined
} from '@ant-design/icons';
import { useForm } from "antd/es/form/Form";
import { JdUnit, deleteJdUnitById, useAddJdUnit, useGetJdUnit, useUpdateJdUnit } from "../../../service/jd-unit-service";
import { ErrorBox } from "../../../components/error-box";
const JdUnitPage = () => {
  const [queryForm] = useForm();
  const [jdFrom] = useForm();
  const [formOpen, setFormOpen] = useState<boolean>();
  const [updateJdUnit, setUpdateJdUnit] = useState<JdUnit>();
  const [queryParams, setQueryParams] = useState<{
    page: number,
    limit: number,
    jdUnitName: string
  }>({
    page: 1,
    limit: 10,
    jdUnitName: ''
  });

  /**搜索街道 */
  const searchData = (value: { jdUnitName: string }) => {
    setQueryParams({
      ...queryParams,
      jdUnitName: value.jdUnitName,
    });
  };

  /**
   * 重置搜索
   */
  const resetQueryParams = () => {
    setQueryParams({
      page: 1,
      limit: 10,
      jdUnitName: ''
    });
    queryForm.resetFields();
  }

  //添加/修改街道
  const okJdFormHandler = async () => {
    if (updateJdUnit) {
      //更新
      const isPass = jdFrom.validateFields();
      if (!isPass) {
        return;
      }
      const values = await jdFrom.getFieldsValue();
      await updateMutation({ ...values, jdUnitId: updateJdUnit.jdUnitId });
      refetch?.();
      setFormOpen(false)
      setUpdateJdUnit(undefined);
    } else {
      //添加
      const isPass = jdFrom.validateFields();
      if (!isPass) {
        return;
      }
      const values = await jdFrom.getFieldsValue();
      await addMutation({ ...values });
      refetch?.();
      setFormOpen(false)
      setUpdateJdUnit(undefined);
    }
  }

  //打开修改模态框
  const updateHandler = (project: JdUnit) => {
    setUpdateJdUnit(project);
    setFormOpen(true)
  }
  //删除
  const removeUnitHandler = (jdUnitId: string) => {
    Modal.confirm({
      title: '⚠️警告',
      content: '你确认执行改操作吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await deleteMutation({ jdUnitId });
        refetch();
      },
    });
  }
  const columns = [
    {
      title: '街道名称',
      dataIndex: 'jdUnitName',
    },
    {
      title: '更多操作',
      render(project: JdUnit) {
        return (
          <div>
            <Button style={{ marginRight: '1.2rem' }} onClick={() => updateHandler(project)}>
              修改
            </Button>
            <Button loading={DIsLoading} danger onClick={() => removeUnitHandler(project.jdUnitId)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];


  /**
  *!删除街道HOOK
  */
  const { mutateAsync: deleteMutation, isLoading: DIsLoading } = deleteJdUnitById();
  /**
   *!获取街道HOOK
   */
  const { isLoading, isError, data: dataSource, error, refetch } = useGetJdUnit(queryParams);

  /**
  * !添加街道Hook
  */
  const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddJdUnit();
  /**
   * !修改街道Hook
   */
  const { mutateAsync: updateMutation, isLoading: UIsLoading } = useUpdateJdUnit();
  /**
   * 分页配置
   */
  const paginationProps = {
    total: dataSource?.count,
    pageSize: queryParams.limit,
    current: queryParams.page,
    showTotal: (count: number) => {
      return `共 ${count} 条`;
    },
    onChange: (pageNum: number) => {
      setQueryParams({ ...queryParams, page: pageNum });
    },
  };
  return (
    <>
      <TableHeader>
        <Form onFinish={searchData} style={{ width: "100%" }} form={queryForm}>
          <Row gutter={16}>
            <Col span={10}>
              <Form.Item label="街道名称" name={"jDUnitName"}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={10}>
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SearchOutlined />}
                  >
                    搜索
                  </Button>
                  <Button type="primary" onClick={() => resetQueryParams()}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Flex gap="small" justify="flex-end">
                <Form.Item>
                  <Button
                    type={"primary"}
                    icon={<PlusOutlined />}
                    onClick={() => {
                      setFormOpen(true);
                    }}
                  >
                    添加
                  </Button>
                </Form.Item>
              </Flex>
            </Col>
          </Row>
        </Form>
      </TableHeader>
      <TableContainer>
        {isError ? (
          <ErrorBox error={error as { message: string }} />
        ) : (
          <Table rowSelection={{ type: 'checkbox' }} dataSource={dataSource?.list} columns={columns} loading={isLoading || DIsLoading} rowKey={(row) => row?.jdUnitId} pagination={paginationProps} />
        )}
      </TableContainer>
      <Modal title="街道"
        centered
        open={formOpen}
        onOk={() => okJdFormHandler()}
        onCancel={() => setFormOpen(false)}
        okText={"确认"}
        cancelText={"取消"}
        confirmLoading={addIsLoading || UIsLoading}
        width={'400px'}>
        <Form style={{ width: '100%' }} form={jdFrom}>
          <Form.Item label="街道名称" name={'jdUnitName'}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>

  );
};

export default JdUnitPage;
